<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 资金明细
 *
 * @icon fa fa-circle-o
 */
class Fwtx extends Backend
{

    /**
     * Fwtx模型对象
     * @var \app\admin\model\deerhome\Fwtx
     */
    protected $model = null;
    protected $searchFields = 'worker.uname';
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\deerhome\Fwtx;
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    public function index()
    {
        if (!$this->request->isAjax())
        {
            return $this->view->fetch();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
   
        $list = $this->model
                ->with(["worker","user"])
                ->where($where)
                ->where("fwtx.type","in",["服务提现","分销提现"])
                ->order($sort, $order)
                ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];

        return json($result);
    }
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if(!isset($params['status'])){
            $this->error('请选择审核状态');
        }
        if(!\in_array($params['status'],[2,3])){
            $this->error('请选择审核状态');
        }
        $userTxed=0;
        if($row['deerhome_user_id']>0){
            $userTxed=Db::name("deerhome_worker_money_log")->where("status",2)->where("type","分销提现")->where('deerhome_user_id',$row['deerhome_user_id'])->SUM('price');
        }
        if($row['jz_worker_id']>0){
            $userTxed=Db::name("deerhome_worker_money_log")->where("status",2)->where("type","服务提现")->where('jz_worker_id',$row['jz_worker_id'])->SUM('price');
        }
        

        if($params['status']==2){
            if($params['note']==""){
                $params['note']="已转账";
            }
            $userTxed=bcadd($userTxed,$row['price'],2);
        }
        if($params['status']==3){
            if(empty($params['note'])){
                $this->error('请在备注填写拒绝原因');
            }
        }
        if($userTxed<0){
            $userTxed*=-1;
        }
        

        $admin=$this->auth->getUserInfo();
        $params['sh_ren']=$admin['username'];
        $params['donetime']=date('Y-m-d H:i:s');
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $result = $row->allowField(true)->save($params);
            //重新计算分销已提现金额
            if($row['deerhome_user_id']>0){
                Db::name("deerhome_user")->where('id',$row['deerhome_user_id'])->update(['wallet_tx'=>$userTxed]);
            }
            //重新计算分销已提现金额
            if($row['jz_worker_id']>0){
                Db::name("deerhome_worker")->where('id',$row['jz_worker_id'])->update(['money_tx'=>$userTxed]);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        try{
            if($row['jz_worker_id']>0){
                \Tools\Msg::toWorkerMoneyGet($row['jz_worker_id'],$params['status']==2?'已转账':'被拒绝',$row['price'],$params['note']);
            }
            if($row['deerhome_user_id']>0){
                \Tools\Msg::toAgentMoneyGet($row['deerhome_user_id'],$params['status']==2?'已转账':'被拒绝',$row['price'],$params['note']);
            }
        }catch(\Exception $e){
            \think\Log::error("提现审核通知失败：".$e->getMessage()."\n".json_encode($row,JSON_UNESCAPED_UNICODE));
        }
        $this->success();

    }
}
